// vue 项目注掉该行
const WebSocket = require('ws');

// CONNECTING: 0
// OPEN: 1
// CLOSING: 2
// CLOSED: 3

class WsClient {
    constructor(url) {
        this.url = url;
        this.reconnectInterval = 5000;
        this.socket = null;
        this.connect();
    }

    connect() {
        this.socket = new WebSocket(this.url);

        this.socket.onopen = () => {
            console.log('✅ WebSocket 已连接');
            if (this.onOpen) this.onOpen();
        };

        this.socket.onmessage = (event) => {
            if (this.onMessage) this.onMessage(event.data);
        };

        this.socket.onclose = () => {
            console.log('❌ 连接关闭，尝试重连...');
            setTimeout(() => this.connect(), this.reconnectInterval);
        };

        this.socket.onerror = (err) => {
            console.error('⚠️ 连接错误:', err);
        };
    }

    send(data) {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(JSON.stringify(data));
        } else {
            console.warn('⚠️ 无法发送，连接未就绪');
        }
    }

    setOnMessage(handler) {
        this.onMessage = handler;
    }

    setOnOpen(handler) {
        this.onOpen = handler;
    }

    close() {
        this.socket.close()
    }
}

module.exports = WsClient;
